<template>
  <div :id="`wft-senior-container-${curComp.id}`" @dblclick.stop="containerDblclick" @contextmenu="seniorContainerContextHandler" :class="['wft-senior-container', { 'wft-container-glowing': curComp.config.isEnchase }]">
    <DynamicComp
      v-for="comp in curComp.children"
      :key="comp.id"
      :ref="`dynamic-draggable-child-${comp.id}`"
      :curComp="comp"
      :isConflictCheck="isConflictCheck"
      :style="{ 'pointer-events': curComp.config.isEnchase ? 'auto' : 'none' }"
      @getRefLineParams="getRefLineParams"
      @onActivated="curComp => $emit('onActivated', curComp)"
      @compContext="(e, curComp) => $emit('compContext', e, curComp)"
    />
    <!--辅助线-->
    <span class="ref-line v-line"
      v-for="item in vLine"
      v-show="item.display"
      :key="item.id"
      :style="{ left: item.position, top: item.origin, height: item.lineLength }"
    />
    <span class="ref-line h-line"
      v-for="item in hLine"
      v-show="item.display"
      :key="item.id"
      :style="{ top: item.position, left: item.origin, width: item.lineLength }"
    />

    <!-- 画板右键 -->
    <SeniorContainerContextPanel
      v-if="showSeniorContainerPanelContext"
      v-bind="contextConfig"
      v-model="idGlobal"
      :curComp="curComp"
      :curCopyComp="curCopyComp"
      :id="`wft-senior-container-${curComp.id}`"
    />

    <!-- 文字提示 -->
    <div class="senior-container-tip" v-show="!curComp.config.isEnchase && !curComp.children.length">双击切换状态</div>
  </div>
</template>
<script>
import DynamicComp from '../../../index/Layout/Panel/Dynamic/index.vue'
import { deepClone, getUuid } from '../../../utils'
import SeniorContainerContextPanel from './seniorContainerContext.vue'
import Bus from '../../../utils/bus'
export default {
  name: 'seniorContainer',
  data() {
    return {
      contextConfig: {
        top: 0,
        left: 0,
        right: 'none',
        bottom: 'none'
      },
      showSeniorContainerPanelContext: false,
      idGlobal: 100,  // 用于生成随机字段使用
      timer: null,
      vLine: [],
      hLine: []
    }
  },
  components: { DynamicComp, SeniorContainerContextPanel },
  props: {
    curComp: {
      type: Object,
      required: true
    },
    isConflictCheck: {
      type: Boolean,
      default: false
    },
    curCopyComp: {
      type: [Object, null],
      default: () => null
    }
  },
  watch: {
    'curComp.children': {
      handler() {
        this.$nextTick(() => {
          if(this.timer) clearTimeout(this.timer)
          this.timer = setTimeout(() => {
            this.initParentSize()
            this.initData()
          }, 200)
        })
      },
      deep: true
    }
  },
  mounted() {
    Bus.$on('hideSeniorContainerPanelContext', this.hideSeniorContainerPanelContext)
    this.initParentSize()
  },
  beforeDestroy() {
    Bus.$off('hideSeniorContainerPanelContext', this.hideSeniorContainerPanelContext)
    if(this.timer) {
      clearTimeout(this.timer)
      this.timer = null
    }
  },
  methods: {
    // 容器右键
    seniorContainerContextHandler(event) {
      if(this.curComp.config.isEnchase) {
        event.stopPropagation()
        event.preventDefault()
        this.hideSeniorContainerPanelContext()
        this.initContextPosition(event)
        this.showSeniorContainerPanelContext = true
      }
    },
    // 隐藏右键面板
    hideSeniorContainerPanelContext() {
      this.showSeniorContainerPanelContext = false
    },
    // 初始化右键面板位置
    initContextPosition(event) {
      const { left, top } = document.getElementById(`wft-senior-container-${this.curComp.id}`).getBoundingClientRect()
      this.contextConfig.top = event.clientY - top
      this.contextConfig.left = event.clientX - left
      this.contextConfig.right = 'none'
      this.contextConfig.bottom = 'none'
    },
    // 初始化父元素大小
    initParentSize() {
      if(this.curComp.children && this.curComp.children.length) {
        this.curComp.children.forEach(item => {
          this.$refs[`dynamic-draggable-child-${item.id}`][0].checkParentSize()
        })
      }
    },
    // 初始化容器组件数据
    initData() {
      this.curComp.data = []
      const item = {}
      if(this.curComp.children && this.curComp.children.length) {
        this.curComp.children.forEach(child => {
          item[child.field] = JSON.parse(JSON.stringify(child.data))
        })
      }
      this.curComp.data.push(item)
    },
    // 双击可以拖动进来
    containerDblclick() {
      this.curComp.config.isEnchase = !this.curComp.config.isEnchase
      this.curComp.config.draggable = !this.curComp.config.isEnchase
      this.curComp.config.resizable = !this.curComp.config.isEnchase
      if(this.curComp.config.isEnchase) {
        this.initParentSize()
        this.startEvent()
      } else {
        this.clearEvent()
      }
    },
    // 监听事件
    startEvent() {
      const seniorContainer = document.getElementById(`wft-senior-container-${this.curComp.id}`)
      seniorContainer.addEventListener('dragover', this.compDragover)
      seniorContainer.addEventListener('drop', this.compDrop)
    },
    // 清除事件
    clearEvent() {
      const seniorContainer = document.getElementById(`wft-senior-container-${this.curComp.id}`)
      seniorContainer.removeEventListener('dragover', this.compDragover)
      seniorContainer.removeEventListener('drop', this.compDrop)
    },
    compDragover(e) {
      e.preventDefault()
    },
    // 松开拖拽组件
    compDrop(event) {
      if(!event.dataTransfer?.getData('dragData')) return
      const dragData = JSON.parse(event.dataTransfer.getData('dragData'))
      if(dragData.curCom.type == 'senior') {
        return this.$message.warning('容器组件不可再嵌套高级组件！')
      }
      if(dragData.curCom.type == 'form') {
        return this.$message.warning('容器组件不可再嵌套表单组件！')
      }
      const curCom = deepClone(dragData.curCom)
      curCom.id = getUuid()
      const seniorContainer = document.getElementById(`wft-senior-container-${this.curComp.id}`)
      const { left, top, width, height } = seniorContainer.getBoundingClientRect()
      curCom.grid.top = Math.floor(event.clientY - top - dragData.offsetY)
      curCom.grid.left = curCom.resizeGrid.width == '100%' ? 0 : Math.floor(event.clientX - left - dragData.offsetX)
      curCom.resizeGrid.top = ((curCom.grid.top / height) * 100).toFixed(0) + '%'
      curCom.resizeGrid.left = ((curCom.grid.left / width) * 100).toFixed(0) + '%'
      if(curCom.resizeGrid.width == '100%') {
        curCom.grid.width = parseInt(width)
      } else {
        curCom.resizeGrid.width = ((curCom.grid.width / width) * 100).toFixed(0) + '%'
      }
      curCom.resizeGrid.height = ((curCom.grid.height / height) * 100).toFixed(0) + '%'
      curCom.config.isActive = true
      curCom.parentId = this.curComp.id
      curCom.parentCompKey = this.curComp.compKey
      curCom.field = curCom.compKey + 'Field' + this.idGlobal++
      this.curComp.children?.forEach(item => item.config.isActive = false)
      this.curComp.children?.push(curCom)
      this.$emit('onActivated', curCom)
      Bus.$emit('addStack')
      Bus.$emit('startEventKeydown')
      if(event.dataTransfer?.getData('dragData')) {
        event.dataTransfer.clearData('dragData')
      }
      this.$nextTick(() => {
        this.$refs[`dynamic-draggable-child-${curCom.id}`][0].checkParentSize()
      })
    },
    // 辅助线回调事件
    getRefLineParams (params) {
      const { vLine, hLine } = params
      let id = 0
      this.vLine = vLine.map(item => {
        item['id'] = ++id
        return item
      })
      this.hLine = hLine.map(item => {
        item['id'] = ++id
        return item
      })
    }
  }
}
</script>
<style scoped>
.wft-senior-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.senior-container-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 14px;
  color: #999;
}

.wft-container-glowing {
  box-shadow: 0 0 0 #d3e3fd, 0 0 10px #d3e3fd, 0 0 10px #d3e3fd, 0 0 30px #d3e3fd;
  cursor: auto;
}

.ref-line{
  position: absolute;
  background-color: rgba(8, 109, 109, .5);
  z-index: 9999;
}
.v-line{
  width: 1px;
}
.h-line{
  height: 1px;
}
</style>
